const router = require("koa-router")();
const ArticleModel = require("../../models/article");
const MovieModel = require("../../models/movie");
const UserModel = require("../../models/users");
router.get("/api/history", async ctx => {
    var { m, id } = ctx.query;
    var item;
    if (m == "article") {
        // 文章历史搜索
        var item = await ArticleModel.find({ _id: id });
        // 查看是否数据已经存在
        var isHaveArticles = await UserModel.find({ "historyArticles._id": id });
        if (isHaveArticles.length == 0) {
            await UserModel.updateOne({}, { $push: { historyArticles: item[0] } });
            ctx.body = {
                code: 200,
                msg: "数据已添加!"
            }
        } else {
            ctx.body = {
                code: 400,
                msg: "数据已存在!"
            }
        }
    } else {
        var table = ["top250", "inTheaters", "comingSoon"];
        var res = {};
        for (let m of table) {
            // 电影历史搜索
            var item = await MovieModel(m).find({ _id: id });
            if(item.length != 0){
                res = item[0];
            }
        }
        // 查看是否数据已经存在
        var isHaveMovies = await UserModel.find({ "historyMovies._id": id });
        if (isHaveMovies.length == 0) {
            await UserModel.updateOne({}, { $push: { historyMovies: res } });
            ctx.body = {
                code: 200,
                msg: "数据已添加!"
            }
        } else {
            ctx.body = {
                code: 400,
                msg: "数据已存在!"
            }
        }


    }
})
module.exports = router;